package edu.gdkm.web.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import edu.gdkm.service.iface.UserService;
import edu.gdkm.sql.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/home")
@CrossOrigin
@ResponseBody
public class UserController {
    @Autowired
    private UserService userService;
    @RequestMapping("/login")
    public User login(@RequestBody User user, HttpSession session) {
        User usersql = userService.findByUsername(user.getUsername());

        if(usersql != null && usersql.getPassword().equals(DigestUtils.md5DigestAsHex((user.getPassword()+usersql.getSalt()).getBytes()))) {
            session.setAttribute("login", usersql.getId());
        }
        System.out.println(session.getId());
        return usersql;
    }
    @RequestMapping("/user")
    public User user(@RequestBody User user,HttpSession session) {
        System.out.println(session.getId());
        User usersql = userService.findByUsername(user.getUsername());
        return usersql;
    }
    @RequestMapping("/register")
    public User register(@RequestBody User user) {

        user.setPassword(DigestUtils.md5DigestAsHex((user.getPassword()+"gdkm").getBytes()));
        user.setSalt("gdkm");
        user.setAvatar("");
        userService.save(user);
        return user;
    }
}
